package com.xiaolin.redissiondemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaolin.redissiondemo.mapper.StorageMapper;
import com.xiaolin.redissiondemo.model.Storage;
import com.xiaolin.redissiondemo.service.StorageService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xiaolin
 * @description 描述
 * @since 2024/5/24
 */
@Service
public class StorageServiceImpl implements StorageService {
    private int storageNum = 1000;
    @Autowired
    private StorageMapper storageMapper;
    private final Lock lock = new ReentrantLock();
    @Autowired
    private RedissonClient redissonClient;

    // @Transactional  // 开启事务与加锁一起使用时操作数据库会有线程安全问题
    @Override
    public String reduceStorage(Integer productId) {
        // synchronized 本地锁
//        synchronized (this) {
//            Storage storage = storageMapper.selectOne(new LambdaQueryWrapper<Storage>().eq(Storage::getProductId, productId));
//            if (storage.getQuantity() > 0) {
//                storage.setQuantity(storage.getQuantity() - 1);
//                storageMapper.updateById(storage);
//            } else {
//                System.out.println("已经没有库存了");
//            }
////            storageMapper.reduceStorage(productId);
////            storageNum--;
////            System.out.println(storageNum);
//        }
        // Lock 本地锁
//        try {
//            lock.lock();
//            Storage storage = storageMapper.selectOne(new LambdaQueryWrapper<Storage>().eq(Storage::getProductId, productId));
//            if (storage.getQuantity() > 0) {
//                storage.setQuantity(storage.getQuantity() - 1);
//                storageMapper.updateById(storage);
//            } else {
//                System.out.println("已经没有库存了");
//            }
//        } finally {
//            lock.unlock();
//        }
        // RLock 分布式琐
        RLock rLock = redissonClient.getLock("redissionLock");
        try {
            rLock.lock();
            Storage storage = storageMapper.selectOne(new LambdaQueryWrapper<Storage>().eq(Storage::getProductId, productId));
            if (storage.getQuantity() > 0) {
                storage.setQuantity(storage.getQuantity() - 1);
                storageMapper.updateById(storage);
            } else {
                System.out.println("已经没有库存了");
            }
        } finally {
            rLock.unlock();
        }
        return "库存扣减成功";
    }
}
